package com.hsyt.pms.security.service.impl;

import com.hsyt.pfc.support.rpc.PageResult;
import com.hsyt.pms.api.common.PageParam;
import com.hsyt.pms.security.dao.UserDao;
import com.hsyt.pms.security.entity.*;
import com.hsyt.pms.security.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.crypto.password.StandardPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @ClassName: UserServiceImpl
 * @Description: 用户接口服务实现
 * @author swang
 * @date 2017年4月17日 下午7:58:22
 */
@Service
public class UserServiceImpl implements UserService {

	private static final Logger LOGGER = LoggerFactory.getLogger(UserServiceImpl.class);

	//	/^(\w)+(\.\w+)*@(\w)+((\.\w{2,3}){1,3})$/
	private static final String emailRegex = "(\\w)+(\\.\\w+)*@(\\w)+((\\.\\w{2,3}){1,3})";
	//	/^(\w)+(\&\w+)+$/
	private static final String phoneRegex = "1[3-9][0-9]\\d{8}";
	
	@Autowired
	private UserDao userDao;

	@Transactional
	@Override
	public UserDetailVo findUserByUserName(String userName) {
		if(StringUtils.isBlank(userName) || userName.length()>64){
			return null;
		}
		if(userName.matches(emailRegex)){
			return userDao.findUserByEmail(userName);
		}
		if(!userName.matches(phoneRegex)){
			return userDao.findUserByUserName(userName);
		}
		// 剩下的是手机号格式，可能需要匹配phone_no，也有可能要匹配user_name
		Long phoneNo = Long.parseLong(userName);
		UserDetailVo userDetail = userDao.findUserByPhoneNo(phoneNo);
		if(userDetail!=null && userDetail.getUserId()!=null && userDetail.getUserId()>0){
			return userDetail;
		}
		userDetail = userDao.findUserByUserName(userName);
		if(userDetail!=null && userDetail.getUserId()!=null && userDetail.getUserId()>0){
			// 更新user_name中的手机号到phone_no字段中
			userDao.updatePhoneNoByUserName(new UserDetailDto(userName, phoneNo));
			return userDetail;
		}
		return userDetail;
	}
	
	/**
	 * <p>Title: insertUserSelective</p>
	 * <p>Description:根据传递的非空参数，新增用户信息 </p>
	 * @param sysUser
	 */
	@Transactional
	@Override
	public void insertUserSelective(SysUser sysUser) {
		userDao.insertUserSelective(sysUser);
	}
	
	/**
	 * <p>Title: updateUserbyUserIdSelective</p>
	 * <p>Description: 根据传递的非空参数，更新用户信息</p>
	 * @param sysUser
	 */
	@Transactional
	@Override
	public int updateUserbyUserIdSelective(Long userId, SysUser sysUser) {
		SysUser user = new SysUser();
		BeanUtils.copyProperties(sysUser, user);
		user.setId(userId);
		return userDao.updateUserbyUserIdSelective(user);
	}
	
	/**
	 * <p>Title: isUserNameAvailable</p>
	 * <p>Description: 验证登录关键字是否可用   type 可能为username phoneNo email</p>
	 * @param type
	 * @param value
	 */
	@Override
	public Boolean isUserNameAvailable(String type,String value) {
		if(StringUtils.isBlank(type)||StringUtils.isBlank(value)){
			return false;
		}
		UserDetailVo user = null;
		if("phoneNo".equals(type)){
			Long phoneNo = Long.parseLong(value);
			user = userDao.findUserByPhoneNo(phoneNo);
		}else if("username".equals(type)){
			user = userDao.findUserByUserName(value);
		}else if("email".equals(type)){
			user = userDao.findUserByEmail(value);
		}else {
			throw new IllegalArgumentException("类型错误，type："+type);
		}
		return (user == null)?true:false;
	}
	
	/**
	 * <p>Title: isUserNameAvailable</p>
	 * <p>Description: 验证登录关键字是否可用   type 可能为username phoneNo email</p>
	 * @param id
	 * @param type
	 * @param value
	 */
	@Override
	public Boolean isUserNameAvailable(String id,String type,String value) {
		if(StringUtils.isBlank(type)||StringUtils.isBlank(value)){
			return false;
		}
		UserDetailVo user = null;
		if("phoneNo".equals(type)){
			Long phoneNo = Long.parseLong(value);
			user = userDao.findUserByPhoneNo(phoneNo);
			return (user == null)?true:((user.getUserId()+"").equals(id)?true:false);
		}else if("username".equals(type)){
			user = userDao.findUserByUserName(value);
			return (user == null)?true:((user.getUserId()+"").equals(id)?true:false);
		}else if("email".equals(type)){
			user = userDao.findUserByEmail(value);
			return (user == null)?true:((user.getUserId()+"").equals(id)?true:false);
		}
			return false;
	}
	
	/**
	 * <p>Title: searchUserDataByDto</p>
	 * <p>Description:分页数据查询</p>
	 * @param dto
	 * @return
	 */
	@Override
	public PageResult<SysUser> searchUserDataByDto(UserQueryDto dto) {
		//日志打印测试
		LOGGER.info("用户查询入参：{}",dto.toString());
//	 	PageParam.initPageDto(dto);
        List<SysUser> list = userDao.queryUsersByDto(dto);
        PageResult<SysUser> result = new PageResult<SysUser>();
        result.setResult(true);
        result.setMessage("分页查询成功");
        result.setTotal(userDao.countQueryUserByDto(dto));
        result.setRows(list);
        return result;
	}
	
	/**
	 * 密码加密
	 * @author 王勇琳
	 * @date 2017年7月18日 下午7:11:54
	 * @param rawPwd
	 * @param salt
	 * @return
	 */
	public String genEncriptPwd(String rawPwd, String salt){
		if(StringUtils.isBlank(salt)){
			salt = "";
		}
		PasswordEncoder passwordEncoder = new StandardPasswordEncoder(salt);
		String encodedPassword = passwordEncoder.encode(rawPwd);
		return encodedPassword;
	}
	
	/**
	 * @Title: cleanDisabledAuthority
	 * @Description:清除不在ids中的角色权限
	 * @param userId
	 * @param ids
	 */
	@Transactional
	@Override
	public void cleanDisabledAuthority(Long userId, Long[] ids) {
		userDao.cleanDisabledAuthority(userId, ids);
	}
	
	/**
	 * @Title: roleAuthorize
	 * @Description: 给用户添加ids中的角色权限
	 * @param userId
	 * @param ids
	 */
	@Transactional
	@Override
	public void roleAuthorize(Long userId, Long[] ids) {
		List<UserRoleRefDto> dtos = new ArrayList<UserRoleRefDto>(ids.length);
		Date time =new Date();
		for(int i=0,l=ids.length;i<l;i++){
			UserRoleRefDto dto = new UserRoleRefDto();
    		dto.setUserId(userId);
    		dto.setRoleId(ids[i]);
    		dto.setCreateTime(time);
    		dto.setUpdateTime(time);
    		dtos.add(dto);
    	}
		userDao.cleanDisabledAuthority(userId, ids);
		userDao.roleAuthorize(dtos);
	}
	
	/**
	 * 根据邮箱获取用户信息
	 */
	public UserDetailVo  findUserByEmail(String email){
		return userDao.findUserByEmail(email);
	}

	@Override
	public SysUser findUserDetailById(Long userId) {
		// TODO Auto-generated method stub
		return userDao.findUserDetailById(userId);
	}
	
}
